#include "Tcp.h"
#include <sys/socket.h>
#include <iostream>
#include <arpa/inet.h>
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_LISTEN 10

TcpServer::TcpServer(const char *ip, const unsigned short port)
{
    serverfd = socket(AF_INET, SOCK_STREAM, 0);
    if (serverfd < 0)
    {
        std::cout<<"socket"<<std::endl;
    }
    //1代表启用端口复用，0代表禁用端口复用
    // int opt = 1;
    // setsockopt(*sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(int));
    struct sockaddr_in addr; 
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip);
    if (bind(serverfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
    {
        std::cout<<"bind"<<std::endl;
        close(serverfd);
    }
    if (listen(serverfd, MAX_LISTEN) < 0)
    {
        std::cout<<"listen"<<std::endl;
        close(serverfd);
    }
}



int TcpServer::TcpServerAccept()
{
    struct sockaddr_in clientaddr;
    socklen_t len = sizeof(clientaddr);
    int acceptfd = accept(serverfd, (struct sockaddr *)&clientaddr, &len);
    if (acceptfd >= 0)
    {
        printf("连接到客户端ip:%s, 端口：%d,sockfd:%d\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port), acceptfd);
    }
    else
    {
        perror("accept");
    }
    return acceptfd;
}


bool TcpServer::TcpServerSend(const int clientfd, void *ptr, int size)
{
    if (write(clientfd, ptr, size) <= 0)
    {
        perror("write error");
        return false;
    }
    return true;
}

bool TcpServer::TcpServerRecv(int clientfd, void *ptr, int size)
{
    int ret = read(clientfd, ptr, size);
    if (ret < 0)
    {
        perror("read error");
        return false;
    }
    else if (ret == 0)
    {
        printf("客户端下线\n");
        return false;
    }
    return true;
}

TcpClient::TcpClient(const char *Serverip, const unsigned short Serverport)
{
    clientfd = socket(AF_INET, SOCK_STREAM, 0);
    if (clientfd < 0)
    {
        std::cout<<"socket"<<std::endl;

    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(Serverport);
    addr.sin_addr.s_addr = inet_addr(Serverip);
    if(connect(clientfd,(struct sockaddr*)&addr,sizeof(addr)) < 0)
    {
        std::cout<<"connect"<<std::endl;
        close(clientfd);
    }
}


bool TcpClient::TcpClientSend(void *ptr, int size)
{
   if (write(clientfd, ptr, size) <= 0)
    {
        perror("send error");
        return false;
    }
    return true;
}

bool TcpClient::TcpClientRecv(void *ptr, int size)
{
    int ret = read(clientfd, ptr, size);
    if (ret < 0)
    {
        perror("recv error");
        return false;
    }
    if (ret == 0)
    {
        printf("服务端下线\n");
        return false;
    }
    return true;
}